#include "mysmiles.h"

#include <QDomDocument>
#include <QFile>
#include <QDir>
#include <QTextDocument>

#include <QDebug>

MySmiles::MySmiles(QObject *parent) : QObject(parent)
{
    listOfSmiles = new SmilesListModel( this );
    m_themeSmiles = new SmilesThemeListModel( this );

    this->getBuffThemes();
}

void MySmiles::parseXMLSmiles( const QString &inFile )
{
    QDomDocument xmldoc;

    QFile file( inFile );
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "MySmiles::parseXMLSmiles(): Error open file: [" << inFile << "]: " << (int)file.error();
        return;
    }

    QString parseError;
    bool parseRes = xmldoc.setContent( &file, &parseError );
    if( ! parseRes ) {
        qDebug() << "MySmiles::parseXMLSmiles(): " << parseError;
    }

    listOfSmiles->clearList();

    QDomNodeList listSmNode = xmldoc.elementsByTagName("icon");
    QMap< QString, QString > tmpBuf;


    for( unsigned int n=0; n<listSmNode.length(); n++ )
    {
        QDomNode nodeSmile = listSmNode.item( n );
        QDomNodeList textNodeList = nodeSmile.toElement().elementsByTagName("text");

        QString object = nodeSmile.toElement().elementsByTagName("object").item(0).toElement().text();

        QFileInfo fInf( inFile );
        QString pathToFile = fInf.canonicalPath() + QDir::separator();

        for( unsigned int m=0; m<textNodeList.length(); m++ )
        {
            QString smb = textNodeList.item( m ).toElement().text();
            if( smb.isEmpty() || smb.isNull() || object.isEmpty() || object.isNull() ) { continue; }

            QString f =  pathToFile + object;
            bufOfSmiles[ smb ] = f;

            if( !tmpBuf.contains(f) )
            {
                SmilesItemModel *sim = new SmilesItemModel( this );
                sim->setPicture( bufOfSmiles[ smb ] );
                sim->setText( smb );
                listOfSmiles->append( sim );
                tmpBuf[f] = smb;
            }
            //qDebug() << "** smile:["<<smb<<"] => ["<<object<<"]";
        }
    }

    emit smilesModelChanged();
}



QString MySmiles::parseMsgString( const QString inString ) //Q_INVOKABLE
{
    QString outString = inString;

    QList<QString> listKeys = bufOfSmiles.keys();
    QList<QString>::const_iterator itr;
    for( itr = listKeys.constBegin(); itr != listKeys.constEnd(); itr++ )
    {
        QString smile = *itr;
        int pos = 0;
        //qDebug() << "***>" << pos << " " << smile;
        while( (pos = outString.indexOf( smile, pos )) >= 0 )
        {
            QString subStr1 = outString.mid( 0, pos );
            QString subStr2 = outString.mid( pos + smile.length() );
            QString img_smile = "<img width=\"32\" height=\"32\" alt=\"" + smile + "\" src=\"file://" + bufOfSmiles[ smile ] + "\"/>";
            outString = subStr1 + img_smile + subStr2;
            //qDebug() << outString;
            pos += img_smile.length();
        }
    }

    /* замена переносов строк */
    outString = outString.replace("\n","<br>");

    return outString;
}


void MySmiles::setFile( const QString &_fileXML )
{
    if( _fileXML != fileXML ) //нужна ли эта проверка. При переинициализации файла, парсинга не будет. Спасет только перезапуск
    {
        fileXML = _fileXML;
        this->parseXMLSmiles( _fileXML );

        emit fileChanged();
    }
}


QString MySmiles::htmlToPlainText(const QString inString) const
{
    QTextDocument doc;
    doc.setHtml( inString );
    return doc.toPlainText();
}


void MySmiles::getBuffThemes()
{
    QString s = QString( QDir::separator() );
    QString dirSmileThemes = QDir::home().absolutePath()+s+".config"+s+"meegim"+s+"smiles"+ s ;
    QDir qd( dirSmileThemes );
    qd.setFilter( QDir::Dirs );

    m_themeSmiles->clearList();

    QFileInfoList list = qd.entryInfoList();
    //qDebug() << dirSmileThemes << "|" << list.length() ;
    for  (int i = 0; i < list.size(); ++i )
    {
        QFileInfo dirInfo = list.at(i);
        QString fTheme = dirInfo.absoluteFilePath()+s+"theme.xml";
        if( QFile::exists(fTheme) )
        {
            //qDebug() << "Smiles: " <<fTheme;
            QMap<QString, QString> dataSmiles = this->getTheme( fTheme );
            if( (dataSmiles["file"] != "") && (dataSmiles["name"] != "") )
            {
                SmilesThemeItemModel *item = new SmilesThemeItemModel( this );
                item->setAuthor( dataSmiles["author"] );
                item->setFile( dataSmiles["file"] );
                item->setName( dataSmiles["name"] );
                item->setPicture( "file://" +dirInfo.absoluteFilePath()+ s + dataSmiles["picture"] );
                m_themeSmiles->append( item );
            }
        }
    }

    //for /opt/meegim/smiles - default
    QString defaultDir = "/opt/meegim/smiles";
    QMap<QString, QString> dataSmiles = this->getTheme( defaultDir + s + "theme.xml" );
    if( (dataSmiles["file"] != "") && (dataSmiles["name"] != "") )
    {
        SmilesThemeItemModel *item = new SmilesThemeItemModel( this );
        item->setAuthor( dataSmiles["author"] );
        item->setFile( dataSmiles["file"] );
        item->setName( dataSmiles["name"] );
        item->setPicture( "file://" +defaultDir+ s + dataSmiles["picture"] );
        m_themeSmiles->append( item );
    }
}


QMap<QString, QString> MySmiles::getTheme( const QString &fileTheme ) const
{
    QMap<QString, QString> retBuf;
    QDomDocument xmldoc;

    QFile file( fileTheme );
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "MySmiles::getTheme(): Error open file: [" << fileTheme << "]: " << (int)file.error();
        return retBuf;
    }

    QString parseError;
    bool parseRes = xmldoc.setContent( &file, &parseError );
    if( ! parseRes ) {
        qDebug() << "MySmiles::getTheme(): " << parseError;
    }

    QDomElement elementMeta = xmldoc.elementsByTagName("meta").item(0).toElement();
    if( !elementMeta.isNull() )
    {
        QString name = elementMeta.elementsByTagName("name").item(0).toElement().text();
        QString author = elementMeta.elementsByTagName("author").item(0).toElement().text();
        QString picture = elementMeta.elementsByTagName("picture").item(0).toElement().text();
        //qDebug() << "** smiles:" << name << "|" << author;
        retBuf["file"] = fileTheme;
        retBuf["author"] = author;
        retBuf["name"] = name;
        retBuf["picture"] = picture;
    }

    return retBuf;
}
